//
//  AppDelegate.m
//  YiQiTingShu
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 直到世界的尽头. All rights reserved.
//

#import "AppDelegate.h"
#import "FindViewController.h"
#import "DIYViewController.h"
#import "MyViewController.h"
#import "RelaxViewController.h"
#import "ViewController.h"
#import "PlayerButton.h"
#import "Music.h"
#import "LastSongViewController.h"
#import "BNNewFeatureViewController.h"
#import "WWTabBarController.h"

@interface AppDelegate ()

@property (nonatomic, strong) WWTabBarController *tabBarController;
@property(nonatomic, assign)BOOL flag;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    NSLog(@"%@", [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]);

    [ThemeManage shareThemeManage].isNight = [[NSUserDefaults standardUserDefaults] boolForKey:@"Night"];
    [PlayerButton shareButton].isPlay = NO;
    
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.backgroundColor = [UIColor whiteColor];
    [_window makeKeyAndVisible];
    
    _tabBarController = [[WWTabBarController alloc] init];
    _tabBarController.tabBar.translucent = NO;
   
    
    [[PlayerButton shareButton] addTarget:self action:@selector(playButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [[PlayerButton shareButton] addObserver:self forKeyPath:@"isPlay" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"播放的变化"];
//    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction)];
//    swipe.direction = UISwipeGestureRecognizerDirectionUp;
//    [[PlayerButton shareButton] addGestureRecognizer:swipe];
    
    [_tabBarController.view addSubview:[PlayerButton shareButton]];
    [_tabBarController.tabBar NightWithType:UIViewColorTypeNormal];
    
    NSString *key = @"CFBundleVersion";
    // 上一次的使用版本（存储在沙盒中的版本号）
    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    // 当前软件的版本号（从Info.plist中获得）
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
    
    [[UITabBar appearance] setBarTintColor:[ThemeManage shareThemeManage].bgColor];
    
    if ([currentVersion isEqualToString:lastVersion]) { // 版本号相同：这次打开和上次打开的是同一个版本
        [_tabBarController.tabBar NightWithType:UIViewColorTypeNormal];
        self.window.rootViewController = _tabBarController;

    } else { // 这次打开的版本和上一次不一样，显示新特性
        self.window.rootViewController = [[BNNewFeatureViewController alloc] init];
        // 将当前的版本号存进沙盒
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    if ([ThemeManage shareThemeManage].isNight) {
        [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackTranslucent];
    }
    else{
        [[UINavigationBar appearance] setBarStyle:UIBarStyleDefault];
    }
    
    [[Music shareInstance] playMusicWith:[[NSUserDefaults standardUserDefaults] objectForKey:@"playUrl"]];
    //NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"playUrl"]);
    [[Music shareInstance].myPlayer pause];
    [self.window addSubview:[PlayerButton shareButton]];
    return YES;
}


-(void)swipeAction
{
    LastSongViewController *vc = [[LastSongViewController alloc] init];
    vc.trackID = [[NSUserDefaults standardUserDefaults] objectForKey:@"trackID"];
    vc.trackUid = [[NSUserDefaults standardUserDefaults] objectForKey:@"trackUid"];
    vc.albumId = [[NSUserDefaults standardUserDefaults] objectForKey:@"albumId"];
    
//    [self transitionAnimation:vc.view];
    [self.window addSubview:vc.view];
}

#pragma mark 转场动画
-(void)transitionAnimation:(UIView *)view{
    //1.创建转场动画对象
    CATransition *transition=[[CATransition alloc]init];
    
    //2.设置动画类型,注意对于苹果官方没公开的动画类型只能使用字符串，并没有对应的常量定义
    transition.type=@"cube";
    
    //设置子类型
//    if (isNext) {
        transition.subtype=kCATransitionFromBottom;
//    }else{
//        transition.subtype=kCATransitionFromLeft;
//    }
    //设置动画时常
    transition.duration=1.0f;
    
    //3.设置转场后的新视图添加转场动画
//    _imageView.image=[self getImage:isNext];
    [view.layer addAnimation:transition forKey:@"KCTransitionAnimation"];
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    //NSLog(@"%@", change);
    if ([[change objectForKey:@"new"]  isEqual: @1]) {
        [self changeRotation];
    }
    else{
        [self changeRotation];
    }
}

-(void)changeRotation
{
    if ([PlayerButton shareButton].isPlay) {
        CABasicAnimation *basicAnimation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];//控制旋转
        basicAnimation2.fromValue = [NSNumber numberWithInteger:0];
        basicAnimation2.toValue = [NSNumber numberWithInteger:M_PI * 100];
        [basicAnimation2 setDuration:1000];//整个动画所需时间
        [basicAnimation2 setRepeatCount:NSIntegerMax];
        [[PlayerButton shareButton].imageView.layer addAnimation:basicAnimation2 forKey:@"rotation"];
        [[Music shareInstance].myPlayer play];
    }
    else{
        [[PlayerButton shareButton].imageView.layer removeAllAnimations];
        [[Music shareInstance].myPlayer pause];
    }
    
}

-(void)playButtonAction
{
    BOOL isPlay = ![PlayerButton shareButton].isPlay;
    if (isPlay) {
        [[PlayerButton shareButton] setIsPlay:YES];
    }
    else{
        [[PlayerButton shareButton] setIsPlay:NO];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

#pragma mark 响应控制台点击事件
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    if (event.type == UIEventTypeRemoteControl) {
        
        switch (event.subtype) {
                
            case UIEventSubtypeRemoteControlPause:
                //暂停按钮
                [[Music shareInstance].myPlayer pause];
                
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                //上一曲
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                //下一曲
                break;
            case UIEventSubtypeRemoteControlPlay:
                //播放按钮
            {
                if (_flag == 1) {
                    [[Music shareInstance].myPlayer play];
                    _flag = 0;
                }
                else
                {
                    [[Music shareInstance].myPlayer pause];
                    _flag =1;
                }
            }
                break;
            default:
                break;
        }
    }
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[NSUserDefaults standardUserDefaults] setObject:[Music shareInstance].currentURL forKey:@"playUrl"];
    [[NSUserDefaults standardUserDefaults] setObject:[PlayerButton shareButton].imageURL forKey:@"picURL"];
}

@end
